package com.core.zyyz.amc.modules.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.core.common.utils.StringUtils;
import com.core.common.utils.uuid.UUID;
import com.core.zyyz.amc.modules.domain.AmcCodeManage;
import com.core.zyyz.amc.modules.domain.AmcSystemConfigB;
import com.core.zyyz.amc.modules.service.AmcCodeManageService;
import com.core.zyyz.amc.modules.service.AmcSystemConfigBService;
import com.core.zyyz.util.PublicUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.core.common.annotation.Log;
import com.core.common.core.controller.BaseController;
import com.core.common.core.domain.AjaxResult;
import com.core.common.enums.BusinessType;
import com.core.zyyz.amc.modules.domain.AmcSystemAttachmentsB;
import com.core.zyyz.amc.modules.service.AmcSystemAttachmentsBService;
import com.core.common.utils.poi.ExcelUtil;
import com.core.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;
import reactor.core.publisher.Flux;

/**
 * 附件、注释Controller
 *
 * @author lfs
 * @date 2024-12-06
 */
@RestController
@RequestMapping("/upload")
public class AmcSystemAttachmentsBController extends BaseController {

    /**
     * filepath，文件上传路径
     */
    @Value("${sunamc.filepath}")
    private String filepath;

    @Autowired
    private AmcSystemAttachmentsBService amcSystemAttachmentsBService;
    @Autowired
    private AmcSystemConfigBService amcSystemConfigBService;
    @Autowired
    private AmcCodeManageService amcCodeManageService;

    /**
     * 查询附件、注释列表
     */
    @PreAuthorize("@ss.hasPermi('amc:upload:list')")
    @GetMapping("/list")
    public TableDataInfo list(AmcSystemAttachmentsB amcSystemAttachmentsB) {
        startPage();
        List<AmcSystemAttachmentsB> list = amcSystemAttachmentsBService.selectAmcSystemAttachmentsBList(amcSystemAttachmentsB);
        return getDataTable(list);
    }

    /**
     * 导出附件、注释列表
     */
    @PreAuthorize("@ss.hasPermi('amc:upload:export')")
    @Log(title = "附件、注释", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, AmcSystemAttachmentsB amcSystemAttachmentsB)
    {
        List<AmcSystemAttachmentsB> list = amcSystemAttachmentsBService.selectAmcSystemAttachmentsBList(amcSystemAttachmentsB);
        ExcelUtil<AmcSystemAttachmentsB> util = new ExcelUtil<AmcSystemAttachmentsB>(AmcSystemAttachmentsB.class);
        util.exportExcel(response, list, "附件、注释数据");
    }

    /**
     * 获取附件、注释详细信息
     */
    @PreAuthorize("@ss.hasPermi('amc:upload:query')")
    @GetMapping(value = "/{attachmentId}")
    public AjaxResult getInfo(@PathVariable("attachmentId") String attachmentId)
    {
        return success(amcSystemAttachmentsBService.selectAmcSystemAttachmentsBByAttachmentId(attachmentId));
    }

    /**
     * 新增附件、注释
     */
    @PreAuthorize("@ss.hasPermi('amc:upload:add')")
    @Log(title = "附件、注释", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody AmcSystemAttachmentsB amcSystemAttachmentsB)
    {
        return toAjax(amcSystemAttachmentsBService.insertAmcSystemAttachmentsB(amcSystemAttachmentsB));
    }

    /**
     * 修改附件、注释
     */
    @PreAuthorize("@ss.hasPermi('amc:upload:edit')")
    @Log(title = "附件、注释", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AmcSystemAttachmentsB amcSystemAttachmentsB)
    {
        return toAjax(amcSystemAttachmentsBService.updateAmcSystemAttachmentsB(amcSystemAttachmentsB));
    }

    /**
     * 删除附件、注释
     */
    @PreAuthorize("@ss.hasPermi('amc:upload:remove')")
    @Log(title = "附件、注释", businessType = BusinessType.DELETE)
    @DeleteMapping("/{attachmentIds}")
    public AjaxResult remove(@PathVariable String[] attachmentIds)
    {
        return toAjax(amcSystemAttachmentsBService.deleteAmcSystemAttachmentsBByAttachmentIds(attachmentIds));
    }


    /**
     * 上传附件
     * @param uploadFiles
     * @param baseBusinessCode 附件关联业务编码
     * @param baseConfigId  配置主表id
     * @param fileCategoryCode 文件类别代码
     * @param fileCategoryName 文件类别名称
     * @param accesstoryList 文件列表
     * @return
     * @throws IOException
     */
    @PostMapping("/uploadFile")
    @Transactional
    public AjaxResult uploadFile(@RequestBody MultipartFile uploadFiles, @RequestParam String baseBusinessCode, @RequestParam String baseConfigId, @RequestParam(required = false) String fileCategoryCode, @RequestParam(required = false) String fileCategoryName, @RequestParam String accesstoryList) throws IOException {
        PublicUtil publicUtil = new PublicUtil();
        if (!StringUtils.isNotEmpty(baseBusinessCode)) {
            return error("附件关联的业务编码为空，请确认业务编码！");
        }
        String path = filepath + baseBusinessCode + File.separator;
        // 如果没有文件路径就创建
        File doc = new File(path);
        if (!doc.exists()) {
            doc.mkdirs();
        }
        String fileName = uploadFiles.getOriginalFilename().replaceAll(" ", "");  //文件名
        File absoluteUrl = new File(path + fileName);   //绝对路径
        AmcSystemAttachmentsB amcSystemAttachmentsB = new AmcSystemAttachmentsB();
        amcSystemAttachmentsB.setAttachmentId(UUID.randomUUID().toString());  //附件表id
        amcSystemAttachmentsB.setBaseBusinessCode(baseBusinessCode);  //附件关联业务id
        amcSystemAttachmentsB.setAttachUrl("");  //附件链接
        amcSystemAttachmentsB.setFileName(fileName);  //文件名称
        amcSystemAttachmentsB.setFileSize(uploadFiles.getSize());  //文件大小
        amcSystemAttachmentsB.setAbsoluteUrl(path + fileName);  //绝对路径
        amcSystemAttachmentsB.setFileType(fileName.substring(fileName.lastIndexOf(".")));  //文件类型
        amcSystemAttachmentsB.setFileCategoryCode(fileCategoryCode);
        amcSystemAttachmentsB.setFileCategoryName(fileCategoryName);

        if (StringUtils.isNotEmpty(baseConfigId)) {
            AmcSystemConfigB amcSystemConfigB = amcSystemConfigBService.selectAmcSystemConfigBByBaseConfigId(baseConfigId);
            String functionCode = amcSystemConfigB.getBaseBusinessNode();
            AmcCodeManage amcCodeManage = amcCodeManageService.selectAmcCodeManageByFunctionCode(functionCode);
            String functionName = amcCodeManage.getFunctionName();
            amcSystemAttachmentsB.setBaseBusinessNode(functionCode);
            amcSystemAttachmentsB.setBaseBusinessName(functionName);
        }

        try {
            uploadFiles.transferTo(absoluteUrl);//将上传的文件保存在absoluteUrl路径下
//            publicUtil.addPublicMap(amcSystemAttachmentsB, "add");
            amcSystemAttachmentsBService.insertAmcSystemAttachmentsB(amcSystemAttachmentsB);
        }catch (IOException e){
            e.printStackTrace();
            logger.error("上传失败！",e);
        }
        JSONArray jsonArray = getAllAttachments(baseBusinessCode, baseConfigId, JSON.parseArray(accesstoryList));
        return success(jsonArray);
    }

    /**
     * 返回文件列表
     * @param baseBusinessCode
     * @param baseConfigId
     * @param accesstoryList
     * @return
     */
    public JSONArray getAllAttachments(String baseBusinessCode, String baseConfigId, JSONArray accesstoryList) {
        List<AmcSystemAttachmentsB> result = new ArrayList<AmcSystemAttachmentsB>();
        if (StringUtils.isNotEmpty(baseBusinessCode)) {
            AmcSystemAttachmentsB attachmentsB = new AmcSystemAttachmentsB();
            attachmentsB.setBaseBusinessCode(baseBusinessCode);
            result = amcSystemAttachmentsBService.selectAmcSystemAttachmentsBList(attachmentsB);
        }
        //查询关联附件
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("businessCode", baseBusinessCode);
        paramMap.put("baseConfigId", baseConfigId);
//        AccessoryController.searchrRelationFile(result, paramMap);

        for (Object a : accesstoryList) {
            JSONObject jsonObject = (JSONObject) a;
            if (StringUtils.isNotEmpty(jsonObject.getString("attachmentType"))) {
                jsonObject.put("attachmentsBList", result.stream().filter(f -> (jsonObject.getString("fileType").equals(f.getFileCategoryCode())) && jsonObject.getString("attachmentType").equals(f.getATTRIBUTE2())).collect(Collectors.toList()));
            } else {
                jsonObject.put("attachmentsBList", result.stream().filter(f -> (jsonObject.getString("fileType").equals(f.getFileCategoryCode()))).collect(Collectors.toList()));
            }
        }
        return accesstoryList;
    }

}
